use async_trait::async_trait;
use axum::{
    extract::{Path, State},
    http::{HeaderMap, StatusCode, Method, Uri},
    response::Response,
    routing::any,
    Router,
};
use rustcloud_core::{ServiceResult, ServiceRegistry, LoadBalancer, Transport, CircuitBreaker, ServiceInstance, Request};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use std::time::SystemTime;

// 引入新的核心接口
use crate::core::{
    GatewayHandler, GatewayRequest, GatewayResponse, GatewayContext, GatewayResult, GatewayError, GatewayConfig as CoreGatewayConfig
};

/// 网关配置（保持兼容性）
#[derive(Debug, Clone)]
pub struct GatewayConfig {
    pub server_addr: String,
    pub registry_config: rustcloud_core::RegistryConfig,
    pub load_balancer_strategy: rustcloud_core::LoadBalancerStrategy,
    pub circuit_breaker_config: rustcloud_core::CircuitBreakerConfig,
    pub transport_timeout: std::time::Duration,
    pub transport_retries: u32,
    /// 新的统一配置
    pub core_config: CoreGatewayConfig,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            server_addr: "0.0.0.0:8080".to_string(),
            registry_config: rustcloud_core::RegistryConfig::new(
                rustcloud_core::RegistryType::Nacos,
                "127.0.0.1:8848"
            ),
            load_balancer_strategy: rustcloud_core::LoadBalancerStrategy::RoundRobin,
            circuit_breaker_config: rustcloud_core::CircuitBreakerConfig::default(),
            transport_timeout: std::time::Duration::from_secs(5),
            transport_retries: 3,
            core_config: CoreGatewayConfig::default(),
        }
    }
}

/// 网关共享状态
pub struct GatewayState<CB: CircuitBreaker + 'static> {
    pub registry: Arc<dyn ServiceRegistry + Send + Sync>,
    pub load_balancer: Arc<dyn LoadBalancer + Send + Sync>,
    pub transport: Arc<dyn Transport + Send + Sync>,
    pub circuit_breaker: Arc<CB>,
    pub config: GatewayConfig,
}

impl<CB: CircuitBreaker> GatewayState<CB> {
    pub fn new(
        registry: Arc<dyn ServiceRegistry + Send + Sync>,
        load_balancer: Arc<dyn LoadBalancer + Send + Sync>,
        transport: Arc<dyn Transport + Send + Sync>,
        circuit_breaker: Arc<CB>,
        config: GatewayConfig,
    ) -> Self {
        Self {
            registry,
            load_balancer,
            transport,
            circuit_breaker,
            config,
        }
    }
}

/// 基于内存注册中心的简易网关实现
pub struct SimpleGateway<CB: CircuitBreaker + 'static> {
    state: Arc<GatewayState<CB>>,
}

/// 网关处理器适配器，将旧的网关逻辑适配到新的接口
pub struct GatewayHandlerAdapter<CB: CircuitBreaker + 'static> {
    state: Arc<GatewayState<CB>>,
}

impl<CB: CircuitBreaker + 'static> GatewayHandlerAdapter<CB> {
    pub fn new(state: Arc<GatewayState<CB>>) -> Self {
        Self { state }
    }
}

#[async_trait]
impl<CB: CircuitBreaker + 'static> GatewayHandler for GatewayHandlerAdapter<CB> {
    async fn handle(&self, request: GatewayRequest, context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        // 获取目标服务名
        let service_name = request.target_service
            .as_ref()
            .ok_or_else(|| GatewayError::routing("缺少目标服务名", request.path.clone()))?;

        // 发现服务实例
        let instances = self.state.registry.discover(service_name)
            .await
            .map_err(|e| GatewayError::service_discovery(
                format!("服务发现失败: {}", e), 
                service_name.clone()
            ))?;

        if instances.is_empty() {
            return Err(GatewayError::service_discovery(
                "没有可用的服务实例", 
                service_name.clone()
            ));
        }

        // 负载均衡选择实例
        let instance = self.state.load_balancer.select(service_name, &instances)
            .await
            .map_err(|e| GatewayError::load_balance(
                format!("负载均衡失败: {}", e), 
                service_name.clone()
            ))?
            .ok_or_else(|| GatewayError::load_balance(
                "无法选择服务实例", 
                service_name.clone()
            ))?;

        // 转换请求
        let rustcloud_request = self.convert_to_rustcloud_request(&request, &instance)?;
        
        // 使用断路器调用服务
        let start_time = SystemTime::now();
        let response = self.call_service_with_circuit_breaker(
            service_name, 
            rustcloud_request, 
            &instance
        ).await?;
        
        // 计算处理时间
        let processing_time = start_time.elapsed()
            .unwrap_or_default()
            .as_millis() as u64;
        
        // 转换响应
        let gateway_response = self.convert_to_gateway_response(response, processing_time, &instance)?;
        
        Ok(gateway_response)
    }
    
    fn name(&self) -> &str {
        "SimpleGatewayHandler"
    }
    
    async fn health_check(&self) -> bool {
        // 简单的健康检查，检查组件是否可用
        true // 在实际情况中，这里可以检查注册中心、负载均衡器等组件的状态
    }
}

impl<CB: CircuitBreaker + 'static> GatewayHandlerAdapter<CB> {
    /// 转换网关请求为 RustCloud 请求
    fn convert_to_rustcloud_request(
        &self, 
        request: &GatewayRequest, 
        instance: &ServiceInstance
    ) -> GatewayResult<Request> {
        let service_name = request.target_service
            .as_ref()
            .ok_or_else(|| GatewayError::validation("缺少目标服务名"))?;
            
        let mut rustcloud_request = Request::new(
            service_name.clone(),
            request.method.to_string(),
            &request.path
        );
        
        // 设置请求头
        for (name, value) in request.headers.iter() {
            if let Ok(value_str) = value.to_str() {
                rustcloud_request.add_header(name.to_string(), value_str.to_string());
            }
        }
        
        // 设置请求体
        if !request.body.is_empty() {
            rustcloud_request.set_body(request.body.clone());
        }
        
        Ok(rustcloud_request)
    }
    
    /// 使用断路器调用服务
    async fn call_service_with_circuit_breaker(
        &self,
        service_name: &str,
        request: Request,
        instance: &ServiceInstance
    ) -> GatewayResult<rustcloud_core::Response> {
        let state = self.state.clone();
        let service_name_owned = service_name.to_string();
        let instance_owned = instance.clone();
        
        let response = self.state.circuit_breaker.call(
            &service_name_owned,
            Box::new(move || {
                let transport = state.transport.clone();
                let instance = instance_owned.clone();
                let request = request;
                Box::pin(async move {
                    transport.send(request, &instance).await
                })
            })
        ).await
        .map_err(|e| {
            match e {
                rustcloud_core::ServiceError::CircuitBreakerOpen(_) => {
                    GatewayError::network("断路器开启，服务不可用", 
                        crate::core::errors::NetworkErrorType::Other)
                },
                rustcloud_core::ServiceError::ServiceNotFound(_) => {
                    GatewayError::service_discovery("服务未找到", service_name_owned)
                },
                rustcloud_core::ServiceError::NetworkError(msg) => {
                    GatewayError::network(msg, crate::core::errors::NetworkErrorType::Connection)
                },
                rustcloud_core::ServiceError::TimeoutError(msg) => {
                    GatewayError::timeout(msg, self.state.config.transport_timeout.as_millis() as u64)
                },
                _ => GatewayError::internal("内部错误")
            }
        })?;
        
        Ok(response)
    }
    
    /// 转换 RustCloud 响应为网关响应
    fn convert_to_gateway_response(
        &self,
        response: rustcloud_core::Response,
        processing_time: u64,
        instance: &ServiceInstance
    ) -> GatewayResult<GatewayResponse> {
        let status = StatusCode::from_u16(response.status as u16)
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            
        let mut gateway_response = GatewayResponse::new(status);
        
        // 设置响应头
        for (name, value) in &response.headers {
            gateway_response.add_header(name, value);
        }
        
        // 设置响应体
        if let Some(body) = response.body {
            gateway_response.set_body(body);
        }
        
        // 设置元数据
        gateway_response.set_processing_time(processing_time);
        gateway_response.set_service_instance(format!("{}:{}", instance.host, instance.port));
        
        Ok(gateway_response)
    }
    
    /// 从 Axum 请求转换为网关请求
    pub fn convert_from_axum_request(
        service_name: String,
        path: String,
        method: Method,
        headers: HeaderMap,
        body: axum::body::Bytes,
        client_ip: Option<String>
    ) -> GatewayRequest {
        // 构建 URI
        let uri_str = format!("/{}/{}", service_name, path.trim_start_matches('/'));
        let uri = uri_str.parse::<Uri>().unwrap_or_else(|_| Uri::from_static("/"));
        
        let mut request = GatewayRequest::new(method, uri);
        request.headers = headers;
        request.body = body.to_vec();
        request.set_target_service(service_name);
        request.path = format!("/{}", path.trim_start_matches('/'));
        
        if let Some(ip) = client_ip {
            request.set_client_ip(ip);
        }
        
        request
    }
}

/// 保持向后兼容的SimpleGateway实现
impl<CB: CircuitBreaker + 'static> SimpleGateway<CB> {
    pub fn new(state: Arc<GatewayState<CB>>) -> Self {
        Self { state }
    }

    pub async fn run(&self) -> ServiceResult<()> {
        let app = Router::new()
            .route("/:service_name/*path", any(handle_request::<CB>))
            .with_state(self.state.clone());

        let listener = tokio::net::TcpListener::bind(&self.state.config.server_addr)
            .await
            .map_err(|e| rustcloud_core::ServiceError::NetworkError(e.to_string()))?;

        println!("Gateway started on {}", self.state.config.server_addr);

        axum::serve(listener, app)
            .await
            .map_err(|e| rustcloud_core::ServiceError::NetworkError(e.to_string()))?;

        Ok(())
    }

    async fn handle_request_inner( // Removed duplicate CB generic
        State(state): State<Arc<GatewayState<CB>>>,
        Path((service_name, path)): Path<(String, String)>,
        headers: HeaderMap,
        body: axum::body::Bytes,
    ) -> Result<axum::response::Response, StatusCode> {
        // Discover service instances
        let instances = state.registry.discover(&service_name)
            .await
            .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;

        if instances.is_empty() {
            return Err(StatusCode::NOT_FOUND);
        }

        // Load balance and select instance
        let instance = state.load_balancer.select(&service_name,
            &instances
        ).await
            .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
            .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;

        // Convert request headers
        let mut request_headers = HashMap::new();
        for (key, value) in headers.iter() {
            if let Ok(value_str) = value.to_str() {
                request_headers.insert(key.to_string(), value_str.to_string());
            }
        }

        // Build request
        let mut request = Request::new(
            service_name.clone(),
            "GET", // TODO: Set actual HTTP method
            &path
        );

        // Set request headers and body
        for (key, value) in request_headers {
            request.add_header(key, value);
        }

        if !body.is_empty() {
            request.set_body(body.to_vec());
        }

        // Use circuit breaker to call service
        let state_for_circuit_breaker = state.clone(); // Clone state for circuit breaker call
        let state_for_outer_closure = state.clone(); // Clone state for the outer closure
        let service_name_for_outer_closure = service_name.clone(); // Clone service_name for the outer closure
        let instance_for_outer_closure = instance.clone(); // Clone instance for the outer closure
        let request_for_outer_closure = request; // Move request into outer closure

        let response = state_for_circuit_breaker.circuit_breaker.call(
            &service_name_for_outer_closure,
            Box::new(move || {
                let state_for_inner_closure = state_for_outer_closure.clone(); // Clone state for the inner closure
                let instance_for_inner_closure = instance_for_outer_closure.clone(); // Clone instance for the inner closure
                let request_for_inner_closure = request_for_outer_closure; // Move request into inner closure
                Box::pin(async move {
                    state_for_inner_closure.transport.send(request_for_inner_closure, &instance_for_inner_closure).await
                })
            })
        ).await
            .map_err(|e| {
                match e {
                    rustcloud_core::ServiceError::CircuitBreakerOpen(_) => StatusCode::SERVICE_UNAVAILABLE,
                    rustcloud_core::ServiceError::ServiceNotFound(_) => StatusCode::NOT_FOUND,
                    rustcloud_core::ServiceError::NetworkError(_) => StatusCode::BAD_GATEWAY,
                    rustcloud_core::ServiceError::TimeoutError(_) => StatusCode::GATEWAY_TIMEOUT,
                    _ => StatusCode::INTERNAL_SERVER_ERROR,
                }
            })?;

        // Build response
        let mut axum_response = Response::builder()
            .status(response.status);

        // Set response headers
        if let Some(headers) = axum_response.headers_mut() {
            for (key, value) in &response.headers {
                if let Ok(header_name) = key.parse::<axum::http::HeaderName>() {
                    if let Ok(header_value) = axum::http::HeaderValue::from_str(value) {
                        headers.insert(header_name, header_value);
                    }
                }
            }
        }

        let body = if let Some(body) = response.body {
            axum::body::Bytes::from(body)
        } else {
            axum::body::Bytes::new()
        };

        Ok(axum_response
            .body(axum::body::Body::from(body))
            .unwrap())
    }
}

/// 处理所有HTTP请求（使用新的接口）
async fn handle_request<CB: CircuitBreaker + 'static>(
    State(state): State<Arc<GatewayState<CB>>>,
    Path((service_name, path)): Path<(String, String)>,
    method: axum::http::Method,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Result<axum::response::Response, StatusCode> {
    // 创建网关处理器适配器
    let handler = GatewayHandlerAdapter::new(state);
    
    // 转换请求
    let gateway_request = GatewayHandlerAdapter::<CB>::convert_from_axum_request(
        service_name.clone(),
        path,
        method,
        headers,
        body,
        None // TODO: 从连接信息中获取客户端IP
    );
    
    // 创建处理上下文
    let context = Arc::new(GatewayContext::new(gateway_request.id.clone()));
    
    // 使用新的统一接口处理请求
    match handler.handle(gateway_request, context).await {
        Ok(gateway_response) => {
            // 转换为 Axum 响应
            let mut axum_response = Response::builder()
                .status(gateway_response.status);
            
            // 设置响应头
            if let Some(headers) = axum_response.headers_mut() {
                for (name, value) in gateway_response.headers.iter() {
                    if let Ok(header_value) = axum::http::HeaderValue::from_str(
                        value.to_str().unwrap_or_default()
                    ) {
                        headers.insert(name.clone(), header_value);
                    }
                }
            }
            
            let body = axum::body::Bytes::from(gateway_response.body);
            Ok(axum_response
                .body(axum::body::Body::from(body))
                .unwrap())
        },
        Err(error) => {
            // 转换错误为HTTP状态码
            Err(error.status_code())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{GatewayHandler, GatewayRequest, GatewayResponse, GatewayContext, GatewayResult, GatewayError};
    use async_trait::async_trait;
    use axum::http::{Method, Uri, StatusCode};
    use rustcloud_core::{
        ServiceRegistry, LoadBalancer, Transport, CircuitBreaker, ServiceInstance, 
        Request, Response, ServiceResult, ServiceError, RegistryConfig, RegistryType,
        LoadBalancerStrategy, CircuitBreakerConfig, CircuitBreakerState, ServiceWatcher,
        CircuitBreakerMetrics, StrategyInfo
    };
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::time::{Duration, Instant, SystemTime};
    use tokio::sync::{RwLock, Mutex};

    // =============================================================================
    // Mock 实现
    // =============================================================================

    /// Mock服务注册中心
    pub struct MockRegistry {
        instances: Arc<RwLock<HashMap<String, Vec<ServiceInstance>>>>,
        discovery_failure: Arc<Mutex<bool>>,
    }

    impl MockRegistry {
        fn new() -> Self {
            Self {
                instances: Arc::new(RwLock::new(HashMap::new())),
                discovery_failure: Arc::Mutex::new(false),
            }
        }

        async fn add_instance(&self, service_name: &str, instance: ServiceInstance) {
            let mut instances = self.instances.write().await;
            instances.entry(service_name.to_string())
                .or_insert_with(Vec::new)
                .push(instance);
        }

        async fn set_discovery_failure(&self, should_fail: bool) {
            *self.discovery_failure.lock().await = should_fail;
        }
    }

    #[async_trait]
    impl ServiceRegistry for MockRegistry {
        async fn register(&self, _service_name: &str, _instance: ServiceInstance) -> ServiceResult<()> {
            Ok(())
        }

        async fn deregister(&self, _service_name: &str, _instance_id: &str) -> ServiceResult<()> {
            Ok(())
        }

        async fn discover(&self, service_name: &str) -> ServiceResult<Vec<ServiceInstance>> {
            if *self.discovery_failure.lock().await {
                return Err(ServiceError::ServiceNotFound(service_name.to_string()));
            }

            let instances = self.instances.read().await;
            Ok(instances.get(service_name).cloned().unwrap_or_default())
        }

        async fn watch(&self, _service_name: &str) -> ServiceResult<Box<dyn ServiceWatcher>> {
            todo!("Mock实现")
        }

        async fn close(&self) -> ServiceResult<()> {
            Ok(())
        }
    }

    /// Mock负载均衡器
    pub struct MockLoadBalancer {
        selection_failure: Arc<Mutex<bool>>,
        selected_instance_id: Arc<Mutex<Option<String>>>,
    }

    impl MockLoadBalancer {
        fn new() -> Self {
            Self {
                selection_failure: Arc::Mutex::new(false),
                selected_instance_id: Arc::Mutex::new(None),
            }
        }

        async fn set_selection_failure(&self, should_fail: bool) {
            *self.selection_failure.lock().await = should_fail;
        }

        async fn set_selected_instance(&self, instance_id: Option<String>) {
            *self.selected_instance_id.lock().await = instance_id;
        }
    }

    #[async_trait]
    impl LoadBalancer for MockLoadBalancer {
        async fn select(&self, _service_name: &str, instances: &[ServiceInstance]) -> ServiceResult<Option<ServiceInstance>> {
            if *self.selection_failure.lock().await {
                return Err(ServiceError::InternalError("负载均衡失败".to_string()));
            }

            let selected_id = self.selected_instance_id.lock().await;
            if let Some(ref id) = *selected_id {
                return Ok(instances.iter().find(|i| i.id == *id).cloned());
            }

            Ok(instances.first().cloned())
        }

        async fn report(&self, _instance: &ServiceInstance, _success: bool, _response_time: Duration) -> ServiceResult<()> {
            Ok(())
        }

        async fn get_strategy_info(&self) -> ServiceResult<StrategyInfo> {
            Ok(StrategyInfo {
                name: "mock".to_string(),
                params: HashMap::new(),
            })
        }
    }

    /// Mock传输层
    pub struct MockTransport {
        response_status: Arc<Mutex<u16>>,
        response_body: Arc<Mutex<Option<Vec<u8>>>>,
        response_headers: Arc<Mutex<HashMap<String, String>>>,
        send_failure: Arc<Mutex<bool>>,
    }

    impl MockTransport {
        fn new() -> Self {
            Self {
                response_status: Arc::Mutex::new(200),
                response_body: Arc::Mutex::new(Some(b"mock response".to_vec())),
                response_headers: Arc::Mutex::new(HashMap::new()),
                send_failure: Arc::Mutex::new(false),
            }
        }

        async fn set_response(&self, status: u16, body: Option<Vec<u8>>, headers: HashMap<String, String>) {
            *self.response_status.lock().await = status;
            *self.response_body.lock().await = body;
            *self.response_headers.lock().await = headers;
        }

        async fn set_send_failure(&self, should_fail: bool) {
            *self.send_failure.lock().await = should_fail;
        }
    }

    #[async_trait]
    impl Transport for MockTransport {
        async fn send(&self, _request: Request, _instance: &ServiceInstance) -> ServiceResult<Response> {
            if *self.send_failure.lock().await {
                return Err(ServiceError::NetworkError("模拟网络错误".to_string()));
            }

            let status = *self.response_status.lock().await;
            let body = self.response_body.lock().await.clone();
            let headers = self.response_headers.lock().await.clone();

            Ok(Response {
                status,
                headers,
                body,
            })
        }
    }

    /// Mock断路器
    pub struct MockCircuitBreaker {
        call_failure: Arc<Mutex<bool>>,
        is_open: Arc<Mutex<bool>>,
        call_count: Arc<Mutex<usize>>,
    }

    impl MockCircuitBreaker {
        fn new() -> Self {
            Self {
                call_failure: Arc::Mutex::new(false),
                is_open: Arc::Mutex::new(false),
                call_count: Arc::Mutex::new(0),
            }
        }

        async fn set_call_failure(&self, should_fail: bool) {
            *self.call_failure.lock().await = should_fail;
        }

        async fn set_open(&self, is_open: bool) {
            *self.is_open.lock().await = is_open;
        }

        async fn get_call_count(&self) -> usize {
            *self.call_count.lock().await
        }
    }

    #[async_trait]
    impl CircuitBreaker for MockCircuitBreaker {
        async fn call<F, Fut, T>(&self, service_name: &str, operation: F) -> ServiceResult<T>
        where
            F: FnOnce() -> Fut + Send,
            Fut: std::future::Future<Output = ServiceResult<T>> + Send,
            T: Send,
        {
            let mut count = self.call_count.lock().await;
            *count += 1;
            drop(count);

            if *self.is_open.lock().await {
                return Err(ServiceError::CircuitBreakerOpen(service_name.to_string()));
            }

            if *self.call_failure.lock().await {
                return Err(ServiceError::InternalError("模拟调用失败".to_string()));
            }

            operation().await
        }

        async fn get_state(&self, _service_name: &str) -> ServiceResult<CircuitBreakerState> {
            if *self.is_open.lock().await {
                Ok(CircuitBreakerState::Open)
            } else {
                Ok(CircuitBreakerState::Closed)
            }
        }

        async fn get_metrics(&self, _service_name: &str) -> ServiceResult<CircuitBreakerMetrics> {
            Ok(CircuitBreakerMetrics {
                total_requests: *self.call_count.lock().await as u64,
                failed_requests: 0,
                success_rate: 1.0,
                failure_rate: 0.0,
                average_response_time: Duration::from_millis(100),
                state: if *self.is_open.lock().await {
                    CircuitBreakerState::Open
                } else {
                    CircuitBreakerState::Closed
                },
                last_failure_time: None,
                state_change_time: SystemTime::now(),
            })
        }

        async fn force_open(&self, _service_name: &str) -> ServiceResult<()> {
            *self.is_open.lock().await = true;
            Ok(())
        }

        async fn force_close(&self, _service_name: &str) -> ServiceResult<()> {
            *self.is_open.lock().await = false;
            Ok(())
        }

        async fn force_half_open(&self, _service_name: &str) -> ServiceResult<()> {
            Ok(())
        }

        async fn reset(&self, _service_name: &str) -> ServiceResult<()> {
            *self.call_count.lock().await = 0;
            *self.is_open.lock().await = false;
            Ok(())
        }
    }

    // =============================================================================
    // 辅助函数
    // =============================================================================

    fn create_test_instance(id: &str, host: &str, port: u16) -> ServiceInstance {
        ServiceInstance {
            id: id.to_string(),
            service_name: "test-service".to_string(),
            host: host.to_string(),
            port,
            weight: 100,
            healthy: true,
            metadata: HashMap::new(),
            last_heartbeat: SystemTime::now(),
        }
    }

    fn create_test_request(service_name: &str, path: &str) -> GatewayRequest {
        let uri = format!("http://localhost:8080{}", path).parse::<Uri>().unwrap();
        let mut request = GatewayRequest::new(Method::GET, uri);
        request.set_target_service(service_name.to_string());
        request.path = path.to_string();
        request
    }

    fn create_test_context() -> Arc<GatewayContext> {
        Arc::new(GatewayContext::new("test-request-123".to_string()))
    }

    fn create_test_gateway_state() -> Arc<GatewayState<MockCircuitBreaker>> {
        let registry = Arc::new(MockRegistry::new());
        let load_balancer = Arc::new(MockLoadBalancer::new());
        let transport = Arc::new(MockTransport::new());
        let circuit_breaker = Arc::new(MockCircuitBreaker::new());
        let config = GatewayConfig::default();

        Arc::new(GatewayState::new(
            registry,
            load_balancer,
            transport,
            circuit_breaker,
            config,
        ))
    }

    // =============================================================================
    // GatewayHandlerAdapter 测试
    // =============================================================================

    #[tokio::test]
    async fn test_gateway_handler_adapter_success() {
        let state = create_test_gateway_state();
        
        // 添加测试服务实例
        state.registry.add_instance("test-service", 
            create_test_instance("instance-1", "localhost", 8080)).await;
        
        let handler = GatewayHandlerAdapter::new(state);
        let request = create_test_request("test-service", "/api/users");
        let context = create_test_context();
        
        let result = handler.handle(request, context).await;
        assert!(result.is_ok());
        
        let response = result.unwrap();
        assert_eq!(response.status, StatusCode::OK);
        assert_eq!(response.body, b"mock response");
        assert!(response.processing_time > 0);
        assert!(response.service_instance.is_some());
    }

    #[tokio::test]
    async fn test_gateway_handler_adapter_missing_service_name() {
        let state = create_test_gateway_state();
        let handler = GatewayHandlerAdapter::new(state);
        
        let uri = "http://localhost:8080/api/users".parse::<Uri>().unwrap();
        let request = GatewayRequest::new(Method::GET, uri); // 没有设置target_service
        let context = create_test_context();
        
        let result = handler.handle(request, context).await;
        assert!(result.is_err());
        
        if let Err(GatewayError::Routing { message, path }) = result {
            assert!(message.contains("缺少目标服务名"));
            assert_eq!(path, "/api/users");
        } else {
            panic!("Expected Routing error");
        }
    }

    #[tokio::test]
    async fn test_gateway_handler_adapter_service_discovery_failure() {
        let state = create_test_gateway_state();
        
        // 设置服务发现失败
        state.registry.set_discovery_failure(true).await;
        
        let handler = GatewayHandlerAdapter::new(state);
        let request = create_test_request("nonexistent-service", "/api/test");
        let context = create_test_context();
        
        let result = handler.handle(request, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::ServiceDiscovery { message, service_name } => {
                assert!(message.contains("服务发现失败"));
                assert_eq!(service_name, "nonexistent-service");
            },
            _ => panic!("Expected ServiceDiscovery error"),
        }
    }

    #[tokio::test]
    async fn test_gateway_handler_adapter_no_available_instances() {
        let state = create_test_gateway_state();
        let handler = GatewayHandlerAdapter::new(state);
        let request = create_test_request("empty-service", "/api/test");
        let context = create_test_context();
        
        let result = handler.handle(request, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::ServiceDiscovery { message, service_name } => {
                assert_eq!(message, "没有可用的服务实例");
                assert_eq!(service_name, "empty-service");
            },
            _ => panic!("Expected ServiceDiscovery error"),
        }
    }

    #[tokio::test]
    async fn test_gateway_handler_adapter_circuit_breaker_open() {
        let state = create_test_gateway_state();
        
        // 添加服务实例并设置断路器开启
        state.registry.add_instance("test-service", 
            create_test_instance("instance-1", "localhost", 8080)).await;
        state.circuit_breaker.set_open(true).await;
        
        let handler = GatewayHandlerAdapter::new(state);
        let request = create_test_request("test-service", "/api/test");
        let context = create_test_context();
        
        let result = handler.handle(request, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::Network { message, error_type } => {
                assert!(message.contains("断路器开启"));
                match error_type {
                    crate::core::errors::NetworkErrorType::Other => {},
                    _ => panic!("Expected Other network error type"),
                }
            },
            _ => panic!("Expected Network error"),
        }
    }

    #[tokio::test]
    async fn test_gateway_handler_adapter_name() {
        let state = create_test_gateway_state();
        let handler = GatewayHandlerAdapter::new(state);
        
        assert_eq!(handler.name(), "SimpleGatewayHandler");
    }

    #[tokio::test]
    async fn test_gateway_handler_adapter_health_check() {
        let state = create_test_gateway_state();
        let handler = GatewayHandlerAdapter::new(state);
        
        assert!(handler.health_check().await);
    }

    #[test]
    fn test_convert_from_axum_request() {
        let service_name = "user-service".to_string();
        let path = "/api/users/123".to_string();
        let method = Method::POST;
        let mut headers = HeaderMap::new();
        headers.insert("content-type", "application/json".parse().unwrap());
        let body = axum::body::Bytes::from(b"{\"name\":\"test\"}".to_vec());
        let client_ip = Some("192.168.1.100".to_string());
        
        let request = GatewayHandlerAdapter::<MockCircuitBreaker>::convert_from_axum_request(
            service_name.clone(),
            path.clone(),
            method.clone(),
            headers,
            body.clone(),
            client_ip.clone()
        );
        
        assert_eq!(request.method, method);
        assert_eq!(request.path, "/api/users/123");
        assert_eq!(request.target_service, Some(service_name));
        assert_eq!(request.body, body.to_vec());
        assert_eq!(request.client_ip, client_ip);
        assert!(request.headers.contains_key("content-type"));
    }

    #[tokio::test]
    async fn test_simple_gateway_creation() {
        let state = create_test_gateway_state();
        let gateway = SimpleGateway::new(state.clone());
        
        // 验证网关实例创建成功
        assert_eq!(Arc::as_ptr(&gateway.state), Arc::as_ptr(&state));
    }
}
